package org.example.maven.museumuser.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.example.maven.museumuser.common.RedisCommon;
import org.example.maven.museumuser.domain.pojo.Result;
import org.example.maven.museumuser.domain.pojo.user.UserLogin;
import org.example.maven.museumuser.domain.pojo.user.UserRegister;
import org.example.maven.museumuser.service.UserService;
import org.example.maven.museumuser.service.impl.UserDetailsImpl;
import org.example.maven.museumuser.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static org.example.maven.museumuser.domain.pojo.StaticVariable.Phone_Code;
import static org.example.maven.museumuser.domain.pojo.StaticVariable.User_Jwt;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisCommon redisCommon;
    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping("/register")
    @PreAuthorize("permitAll()")
    public Result userRegister(@RequestBody UserRegister userRegister){
        if(redisCommon.getValueOfString(Phone_Code+userRegister.getPhone()).equals(userRegister.getCode())){
            if(userRegister.getPassword().equals(userRegister.getPassword2())){
                if(userService.getUserLoginByPhone(userRegister.getPhone())==null){
                    userService.register(userRegister);
                }else {
                    return Result.error("账号已存在");
                }
            }else {
                return Result.error("两次密码不一致");
            }
        }else {
            return Result.error("验证码错误");
        }
        return Result.success();
    }

    @PostMapping("/login")
    //用户登录
    @PreAuthorize("permitAll()")
    public Result userLogin(@RequestBody UserLogin userLogin) throws JsonProcessingException {
        UserLogin user=userService.getUserLoginByPhone(userLogin.getPhone());
        if(user!=null){
            try {
                Authentication authentication = authenticationManager.authenticate(
                        new UsernamePasswordAuthenticationToken(
                                userLogin.getPhone(),
                                userLogin.getPassword()
                        )
                );
                SecurityContextHolder.getContext().setAuthentication(authentication);
                UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
                Map<String, Object> claims = new HashMap<>();
                claims.put("id",userDetails.getUserLogin().getId());
                claims.put("phone", userDetails.getUserLogin().getPhone());
                String jwt=JwtUtils.getUserJwt(claims);
                redisCommon.setTemporaryCode(User_Jwt+user.getPhone(),jwt,30, TimeUnit.MINUTES);
                System.out.println(jwt);
                return Result.success("登录成功",jwt);
            }catch (BadCredentialsException e){
                return Result.error("账号或者密码错误");
            }
        }else {
            return Result.error("账号未注册");
        }
    }

    @PostMapping("/loginOut")
    @PreAuthorize("permitAll()")
    public Result userLoginOut(){
        Authentication authentication=SecurityContextHolder.getContext().getAuthentication();
        authentication.getPrincipal();
        return Result.success("退出成功");
    }

    @PostMapping("/getUserInfo")
    @PreAuthorize("permitAll()")
    public Result getUserInfo(){
        Authentication authentication=SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        return Result.success(userDetails.getUserLogin());
    }



}
